var showPastEvents = false;
var sinceDate = 0;
var myUser;
var myName;

///////////////////////////////////////
////// General Purpose Functions //////
///////////////////////////////////////

//initiazlie myName and myUser
function getMe() {
	$.get(
			'/'+context+'/resources/users/me'
		).success(function(data){
			myName = data.name;
			myUser = data.username;
			$('#welcome').html("Welcome "+myName);
			initialize();
		}).error(function(data){
			//alert ("Can't retrieve your name! "+data.responseText);
			$.cookie("kuki", null);
			window.location.replace('index.html');
			});
}
//run the functions
$(document).ready(function() {
	getMe();
});


////////////////////////////////////////////////
////// jQuery UI Related Button Functions //////
////////////////////////////////////////////////

// jQuery UI Related Button Functions
$(document).ready(function() {
	$("#kml-options").buttonset();
	$("#ws-keywords-loading").hide();
	$("#ws-location-loading").hide();
	$("#location").click(function(){
	    if( $(this).val() == 'Search for an address...'){
	        $(this).val('');
	    }
	});
	$("#logout_button").button().click(function() {
		$.cookie("kuki", null);
		window.location.replace('index.html');
	});
	$('#find-button').button().click(function() {
		geocode();
	});
	$('#time').datetimepicker();
	$('#sincedate').datepicker();
	$( "#show-past-events" ).button().click(function() {
		if ($(this).is(':checked')) {
			showPastEvents = true;
			google.maps.event.trigger(map, "idle");
			addMine();
		} else {
			showPastEvents = false;
			google.maps.event.trigger(map, "idle");
			addMine();
		}
	});
	$("#set-since").button().click(function(event) {
			var since = $("#sincedate");
			var sinceTime = since.val();
		var tLong = Date.parse(sinceTime,"MM/dd/yyyy HH:MM");
		sinceDate = tLong;
		google.maps.event.trigger(map, "idle");
		addMine();
		alert("Since date has been set to "+sinceTime);
	});
	$("#since-reset").button().click(function(event) {
		sinceDate = 0;
		$("#sincedate").val("");
		google.maps.event.trigger(map, "idle");
		addMine();
		alert("Since date has been reset");
	});
	$("#multiaccordion").addClass("ui-accordion ui-widget ui-helper-reset ui-accordion-icons")
	.find("h3")
	        .addClass("ui-accordion-header ui-helper-reset ui-corner-bottom ui-corner-top ui-state-default")
	        .hover(function() { $(this).toggleClass("ui-state-hover"); })
	        .prepend('<span class="ui-icon ui-icon-triangle-1-e"/>')
	        .click(function() {
	            $(this).toggleClass("ui-accordion-header-active").toggleClass("ui-state-active")
	                .toggleClass("ui-state-default").toggleClass("ui-corner-bottom")
	                .find("> .ui-icon").toggleClass("ui-icon-triangle-1-e").toggleClass("ui-icon-triangle-1-s")
	                .end().next().slideToggle().toggleClass("ui-accordion-content-active");
	            return false;
	        })
	        .next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom").hide();
	$("#clear-search-results").button().click(function() {
		clearSearchResults();
		alert("All search results cleared away!");
	});
	$("#export-xml-button").button().click(function(e) {
	    e.preventDefault();  //stop the browser from following
	    window.location.href = '/'+context+'/resources/messages/xml?noEvents=false';
	});
	$("#kml-button").button().click(function(e) {
		e.preventDefault();  //stop the browser from following
		var msg = $("#messages-only");
		var evt = $("#events-only");
		var path = $("#path");
		if (msg.is(":checked")) {
			window.location.href = '/'+context+'/resources/messages/kml';
		}
		if (evt.is(":checked")) {
			window.location.href = '/'+context+'/resources/events/kml';
		}
		if (path.is(":checked")) {
			window.location.href = '/'+context+'/resources/messages/allPath';
		}
	});
	$( "#create-msg" ).button().click(function() {
		$( "#msg-form" ).dialog( "open" );
	});
	
	$( "#create-event" ).button().click(function() {
		var now = new Date();
		var nowMin = now.getMinutes();
		now.setMinutes(nowMin+5);
		$("#time").datepicker("setDate", now);
		$( "#event-form" ).dialog( "open" );
	});	

	$( "#delete-me" ).button().click(function() {
			$( "#delete-me-form" ).dialog( "open" );
	});
	
	$( "#ws-keywords-search" ).button().click(function() {
		$( "#ws-keywords-form" ).dialog( "open" );
	});
	
	$( "#ws-location-search" ).button().click(function() {
		$( "#ws-location-form" ).dialog( "open" );
	});
	
	$( "#show-users" ).button().click(function() {
		$.get('/'+context+'/resources/users'
				).success(function(data,status,result) {
					var users_html = "";
					var count = 1;
					$.each(data, function(index,user) {
						users_html += '<p>'+count+'. '+user.name+' ('+user.username+')</p>';
						count += 1;
					});
					document.getElementById("users").innerHTML = users_html;
					$( "#users-form" ).dialog( "open" );
				}).error(function(data) {
					alert("Can't retrieve site's users! "+data.responseText);
				});
	});
});

//////////////////////////////////////////
////// Message UI Related Functions //////
//////////////////////////////////////////

//create new msg form
$(function() {
	var content = $( "#content" );
	
	$( "#msg-form" ).dialog({
		autoOpen: false,
		height: 300,
		width: 350,
		modal: true,
		buttons: {
			"Post": function() {
				//get address
				var addr = 'Not Available';
				if(currentReverseGeocodeResponse) {
				     if(currentReverseGeocodeResponse.length == 0) {
				       addr = 'Not Available';
				     } else {
				       addr = currentReverseGeocodeResponse[0].formatted_address;
				     }
				   }
				var msg = content.val();
				$.post(
						'/'+context+'/resources/messages',
						JSON.stringify({content: msg, location: {lat: map.getCenter().lat(), long: map.getCenter().lng(), address: addr}})
					).success(function(data, status, response){
						addMsgAtCenter(response.getResponseHeader("Location"));
					}).error(function(data){
						alert ("Can't post! "+data.responseText);
					}); 
				$( this ).dialog( "close" );
			},
			Cancel: function() {
				$( this ).dialog( "close" );
			}
		},
		close: function() {
		}
	});
});


//////////////////////////////////////////
//////  Event UI Related Functions  //////
//////////////////////////////////////////
function isNumber(n) {
	return n.match(/^\d+$/);
}
//create new event form
$(function() {
	var info = $( "#info" ),
		capacity = $( "#capacity" ),
		time = $( "#time" );

	$( "#event-form" ).dialog({
		autoOpen: false,
		height: 300,
		width: 350,
		modal: true,
		buttons: {
			"Create Event": function() {				
				var information = info.val();
				var cap = capacity.val();
				if (cap === "" || !isNumber(cap)) {
					alert("Please insert a valid number in capacity");
					return;
				}
				var t = time.val();
				var tLong = Date.parse(t,"MM/dd/yyyy HH:MM");
				//get address
				var addr = '';
				
				if(currentReverseGeocodeResponse) {
				     if(currentReverseGeocodeResponse.length == 0) {
				       addr = 'Not Available';
				     } else {
				       addr = currentReverseGeocodeResponse[0].formatted_address;
				     }
				   }
				$.post(
						'/'+context+'/resources/events',
						JSON.stringify({content: information, location: {lat: map.getCenter().lat(), long: map.getCenter().lng(), address: addr}, capacity: parseInt(cap), time: tLong})
					).success(function(data, status, response){
						addEventAtCenter(response.getResponseHeader("Location"));
						alert("Event created successfuly!");
					}).error(function(data){
						alert ("Can't create event! "+data.responseText);
					}); 
				$( this ).dialog( "close" );

			},
			Cancel: function() {
				$( this ).dialog( "close" );
			}
		},
		close: function() {
		}
	});	
});


//////////////////////////////////////////
////// Account UI Related Functions //////
//////////////////////////////////////////

//delete my account form
$(function() {	
	var pass = $( "#password" );
	
	$( "#delete-me-form" ).dialog({
		autoOpen: false,
		height: 240,
		modal: true,
		buttons: {
			"Delete My Account": function() {
				var p = pass.val();
				$.post(
						'/'+context+'/resources/users/'+myUser+'/unregister',
						JSON.stringify({password: p})
					).success(function(){
						alert("Your account has been deleted successfully!");
						$.cookie("kuki", null);
		    			window.location.replace('index.html');
					}).error(function(data){
						alert ("Can't delete your account! "+data.responseText);
					}); 
				$( this ).dialog( "close" );
			},
			Cancel: function() {
				$( this ).dialog( "close" );
			}
		},
		close: function() {
		}
	});
});

//see all users
$(function() {
	$( "#users-form" ).dialog({
		autoOpen: false,
		height: 300,
		width: 350,
		modal: true,
		buttons: {
			"Close": function() {
				$( this ).dialog( "close" );
			},
		},
		close: function() {
			document.getElementById("users").innerHTML = "";
		}
	});		
});

//////////////////////////////////////////////
//////  WebService UI Related Functions //////
//////////////////////////////////////////////

// WS Keywords Search
$(function() {	
	var keywords = $( "#keywords" );
	
	$( "#ws-keywords-form" ).dialog({
		autoOpen: false,
		height: 240,
		modal: true,
		buttons: {
			"Search": function() {
				var keywordsString = keywords.val();
				var keywordsArray = keywordsString.split(/;\s*/g);
				$( "#ws-keywords-search" ).hide();
				$("#ws-keywords-loading").show();
				$.post(
						'/'+context+'/resources/ws/keywords', JSON.stringify(keywordsArray)
					).success(function(data,status,respone){
						$("#ws-keywords-loading").hide();
						$( "#ws-keywords-search" ).show();
						addSearchResults(data,"Keywords");
					}).error(function(data){
						$("#ws-keywords-loading").hide();
						$( "#ws-keywords-search" ).show();
						alert ("Unable to perform WS search! "+data.responseText);
					}); 
				$( this ).dialog( "close" );
			},
			Cancel: function() {
				$( this ).dialog( "close" );
			}
		},
		close: function() {
		}
	});
});

// WS Location Search
$(function() {	
	var radius = $( "#radius" );
	
	$( "#ws-location-form" ).dialog({
		autoOpen: false,
		height: 240,
		modal: true,
		buttons: {
			"Search": function() {
				var r = radius.val();
				var center = map.getCenter();
				var lat = center.lat();
				var lng = center.lng();
				$( "#ws-location-search" ).hide();
				$("#ws-location-loading").show();
				$.post(
						'/'+context+'/resources/ws/local',
						JSON.stringify({locationX: lng, locationY: lat, distance: parseFloat(r)})
					).success(function(data,status,respone){
						$("#ws-location-loading").hide();
						$( "#ws-location-search" ).show();
						addSearchResults(data,"Location");
					}).error(function(data){
						$("#ws-location-loading").hide();
						$( "#ws-location-search" ).show();
						alert ("Unable to perform WS search! "+data.responseText);
					}); 
				$( this ).dialog( "close" );
			},
			Cancel: function() {
				$( this ).dialog( "close" );
			}
		},
		close: function() {
		}
	});
});